<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\cdc\stat;

use app\enum\CommonEnum;
use app\enum\CostServiceCostEnum;
use app\enum\ServiceCostEnum;
use app\model\mongo\MongoSyncModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class QqPicService extends PicStatService implements StatInterface
{
    protected int $mediaId = CommonEnum::QQ_MEDIA;

    protected array $statModelList = [
        CostServiceCostEnum::STAT_ACCOUNT => '\app\model\mongo\MongoQqAccountPicStatModel',
        CostServiceCostEnum::STAT_CLIENT => '\app\model\mongo\MongoQqClientPicStatModel',
        CostServiceCostEnum::STAT_PICTURE => '\app\model\mongo\MongoQqPicStatModel',
    ];

    protected array $recordModelList = [
        CostServiceCostEnum::STAT_ACCOUNT => '\app\model\mongo\MongoQqPicDayReportModel',
        CostServiceCostEnum::STAT_CLIENT => '\app\model\mongo\MongoQqPicDayReportModel',
        CostServiceCostEnum::STAT_PICTURE => '\app\model\mongo\MongoQqPicDayReportModel',
    ];

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function __construct()
    {

    }

    /**
     * 运行数据模型.
     */
    public function runStat(MongoSyncModel $model): bool
    {
        $this->syncModel = $model;
        $lockAccountId = $this->syncModel->getAttr('account_id');
        $lockPicId = $this->syncModel->getAttr('pic_id');
        $lockType = $this->syncModel->getAttr('type');
        $lockKey = sprintf(ServiceCostEnum::CACHE_CONFIG['media_pic_cost_lock'][CommonEnum::QQ_MEDIA], $lockAccountId, $lockPicId, $lockType);
        if (self::lock($lockKey, 1, 120)) {
            if (! $this->setModel()) {
                return false;
            }

            $type = $this->compareStat();
            if ($type == -1) {
                if (! $this->addStatByRecord()) {
                    return false;
                }
            } else {
                if (! $this->sumStat()) {
                    return false;
                }
            }

            return true;
        }

        return self::setError('加锁失败！lock_key:' . $lockKey);
    }

    public function getCost(float $cost = 0): float
    {
        return round($cost / 100, 2);
    }
}
